package com.tao.controller;

import com.tao.config.MyLog;
import com.tao.mapper.MenuMapper;
import com.tao.pojo.Menu;
import com.tao.pojo.User;
import com.tao.pojo.vo.ResponseResult;
import com.tao.pojo.vo.UserVo;
import com.tao.service.LoginService;
import com.tao.service.UserService;
import com.tao.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 登录
     */
    @PostMapping("/user")
    @MyLog(value = "用户登录")
    public HashMap<String, Object> login(@RequestBody User user) {
        return loginService.login(user);
    }

    @PostMapping("/admin")
    @MyLog(value = "管理员登录")
    public HashMap<String, Object> adminLogin(@RequestBody User user) {
        return loginService.adminLogin(user);
    }


    /**
     * 用户注册传入用户名密码
     */
    @PostMapping("/register")
    @MyLog(value = "用户注册")
    public ResponseResult register(@RequestBody User user) {
        return loginService.register(user);
    }

    /**
     * 退出
     */
    @PostMapping("/logout")
    public String logout() {
        return loginService.logout();
    }

    /**
     * 通过用户id获取对应菜单，并返回
     */
    @PostMapping("/menu")
    public HashMap<String, Object> menu(@RequestBody User user) {
        HashMap<String, Object> map = new HashMap<>();
        List<Menu> menus = menuMapper.selectMenuById(user.getId());
        map.put("data", menus);
        return map;
    }

    @MyLog(value = "管理员密码修改")
    @GetMapping("/setpwd")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Object setpwd(@RequestBody User user){
        userService.updateById(user);
        return ResponseResult.success(null);
    }

    /**
     * 测试
     */
    @MyLog(value = "测试日志")
    @GetMapping("/test")
    @PreAuthorize("hasAnyAuthority('admin')")
    public HashMap<String,Object> test() {
        HashMap<String, Object> hashMap = new HashMap<>();
        String jwt = JwtUtil.createJWT("1");
        hashMap.put("data", jwt);
        return hashMap;
    }
}
